<?php

namespace App\Services;

use App\Interfaces\LogInterface;
use Illuminate\Support\Facades\DB;
use Jenssegers\Agent\Agent;

class LogService implements LogInterface
{
    public function __construct()
    {
        $this->agent = new Agent();
    }

    /**
     * 添加登录日志
     * @param $request
     * @param $user
     * @param array $data
     * @return int
     */
    public function addLoginLog($request, $user,array $data): mixed
    {
        $data['userId'] = $user->userId;
        $data['nickname'] = $user->nickname;
        $data['username'] = $user->username;
        $data['createTime'] = $data['updateTime'] = dateTime();
        $data['ip'] = $request->getClientIp();
        $data['device'] = $this->agent->device();
        $platform = $this->agent->platform();
        $data['os'] = $platform.' '.$this->agent->version($platform);
        $browser = $this->agent->browser();
        $data['browser'] = $browser.' '.$this->agent->version($browser);
        $res = DB::table('login_record')->insertGetId($data);
        return $res;
    }

    /**
     * 添加操作日志
     * @param $request
     * @param array $data
     * @return int
     */
    public function addOperateLog($request, array $data): int
    {
        $data['userId'] = $request->userInfo->userId;
        $data['nickname'] = $request->userInfo->nickname;
        $data['username'] = $request->userInfo->username;
        $data['createTime'] = $data['updateTime'] = dateTime();
        $data['requestMethod'] = $request->getRealMethod();
        $data['method'] = $request->route()->getActionMethod();
        $data['spendTime'] = getElapsedTime();
        $data['ip'] = $request->getClientIp();
        $data['url'] = $request->getPathInfo();
        $data['device'] = $this->agent->device();
        $platform = $this->agent->platform();
        $data['os'] = $platform.' '.$this->agent->version($platform);
        $browser = $this->agent->browser();
        $data['browser'] = $browser.' '.$this->agent->version($browser);
        $res = DB::table('operate_record')->insertGetId($data);
        return $res;
    }
}
